package com.hspedu.bot.service.impl.user.bot;

import com.hspedu.bot.pojo.Bot;
import com.hspedu.bot.pojo.User;
import com.hspedu.bot.service.user.bot.BotService;
import com.hspedu.bot.service.user.bot.RemoveService;
import com.hspedu.bot.utils.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class RemoveServiceImpl implements RemoveService {

    @Autowired
    private BotService botService;

    @Override
    public Map<String, String> remove(Map<String, String> data) {

        UsernamePasswordAuthenticationToken authenticationToken
                = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl loginUser
                = (UserDetailsImpl) authenticationToken.getPrincipal();
        User user = loginUser.getUser();

        //获取参数
        Integer bot_id = Integer.parseInt(data.get("bot_id"));
        Bot bot = botService.getById(bot_id);
        Map<String, String> map = new HashMap<>();

        //1.有可能没有这个bot数据
        if (bot == null) {
            map.put("error_message", "Bot不存在或已被删除");
            return map;
        }

        //2.有可能该用户没有权限
        if (bot.getUserId() != user.getId()) {
            map.put("error_message", "没有权限删除该Bot");
            return map;
        }

        //删除bot模型
        botService.removeById(bot.getId());
        map.put("error_message", "success");

        return map;
    }
}
